package org.brownflat.lighthouse.monitor;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.action.Action;
import org.brownflat.lighthouse.ci.Monitorable;
import org.brownflat.lighthouse.device.Device;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

public class BrokenBuildTask implements LighthouseTask {
	
	private Monitorable monitorable;
	private Action whenTrue;
	private Action whenFalse;
	private Action whenResetNeeded;
	private boolean broken = false;
	private String name = null;
	private Device device;
	private static final Logger LOG = Logger.getLogger(BrokenBuildTask.class);


    @Override
    @SuppressWarnings("unchecked")
	public void run() {
		LOG.debug("Checking for any broken build");
		if(monitorable.builds().hasBrokenBuild()) {
			if(!broken) {
				device.execute(whenResetNeeded);
			}
			
			broken = true;
			device.execute(whenTrue);
			LOG.error("BROKEN BUILD DETECTED.");
		} else {
			if(broken) {
				LOG.error("BROKEN BUILD FIXED.");
				device.execute(whenResetNeeded);
			}
			LOG.info("BUILDS OK.");
			broken = false;
			device.execute(whenFalse);
		}
	}

    public Monitorable getMonitorable() {
        return monitorable;
    }

    public void setMonitorable(Monitorable monitorable) {
        this.monitorable = monitorable;
    }

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public boolean isBroken() {
        return broken;
    }

    public void setBroken(boolean broken) {
        this.broken = broken;
    }

    public Action getWhenResetNeeded() {
        return whenResetNeeded;
    }

    public void setWhenResetNeeded(Action whenResetNeeded) {
        this.whenResetNeeded = whenResetNeeded;
    }

    public Action getWhenFalse() {
        return whenFalse;
    }

    public void setWhenFalse(Action whenFalse) {
        this.whenFalse = whenFalse;
    }

    public Action getWhenTrue() {
        return whenTrue;
    }

    public void setWhenTrue(Action whenTrue) {
        this.whenTrue = whenTrue;
    }

    @Override
	public String getName() {
		return name;
	}

    @Override
    public void setName(String name) {
        this.name = name;
    }
}
